package cn.gson.CRM.controller.notice;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

/**
* @author 邓安民:
* @version 创建时间：2018年5月23日 下午5:57:24
* 类说明
*/
@Controller
@RequestMapping("/notice")
public class ImgController {
    @Autowired 
    private HttpServletRequest request; 
    @RequestMapping(value ="/upload",method=RequestMethod.POST)
    @ResponseBody
    public Object UpLoadImg(@RequestParam(value="myFileName")MultipartFile mf) {
        //在工程下创建uploads文件夹
        ServletContext application = request.getServletContext();
        String root = application.getRealPath("");//获取发布后的路径
        String uploads = root + File.separator + "uploads";
        System.out.println(uploads);
        //创建文件夹
        File dir = new File(uploads);
        if(!dir.exists())
             dir.mkdirs();
       
        //生成一个唯一的文件名
        String fileName = UUID.randomUUID().toString()
                  .toUpperCase();//全球唯一标识符
        //获取文件的扩展名
        String originalFilename = mf.getOriginalFilename();
        //获取文件后缀
        int pos = originalFilename.lastIndexOf('.');
        String ext = originalFilename.substring(pos);
        //拼成完整的文件名
        String fullName = fileName + ext;
        //完整的路径+文件名
        File fullFile = new File(dir, fullName);
        System.out.println(fullName);
     
    //开始从源文件拷贝到目标文件
     
    //传图片一步到位
    try {
        mf.transferTo(fullFile);
    } catch (IllegalStateException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
     
    Map<String, String> map = new HashMap<String, String>();
    map.put("data",request.getContextPath()+"/uploads/"+fullName);//这里应该是项目路径
    return map;//将图片地址返回
    }
}
 